package com.example.studentaihouduan.service;

import com.example.studentaihouduan.dto.AIRequest;
import com.example.studentaihouduan.dto.AIResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
public class AIService {

    private final RestTemplate restTemplate;
    private final HttpHeaders aiHeaders;

    @Qualifier("apiUrl")
    private final String apiUrl;

    @Qualifier("slug")
    private final String slug;

    public String askAI(String question) {
        try {
            AIRequest request = new AIRequest(question, "chat");
            HttpEntity<AIRequest> entity = new HttpEntity<>(request, aiHeaders);

            String url = apiUrl + "/api/v1/workspace/" + slug + "/chat";
            ResponseEntity<AIResponse> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    AIResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return processResponse(response.getBody().getTextResponse());
            }
            return "请求失败，状态码: " + response.getStatusCodeValue();
        } catch (Exception e) {
            return "发生异常: " + e.getMessage();
        }
    }

    private String processResponse(String textResponse) {
        if (textResponse.contains("</think>")) {
            String[] parts = textResponse.split("</think>");
            return parts[parts.length - 1].trim();
        }
        return textResponse;
    }
}